package cn.edu.zxj.rabbitmqmyself.util;
import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * Description：
 *
 * @author: zxj
 * @date: 2024-10-02
 * @time: 00:18:30
 */
public class CommandUtil {
    /*
     * 执行命令, 并将结果输出到指定文件
     */
    public static int run(String cmd, String stdout, String stderr)  {
        try {
            // 1. 执行命令, 获取到进程对象
            Process process = Runtime.getRuntime().exec(cmd);
            // 2. 将进程的输出内容保存到 stdout 文件中
            InputStream inputStream = process.getInputStream();
            FileUtil.writeFromStream(stdout, inputStream);

            // 3. 将进程的错误内容保存到 stderr 文件中
            InputStream errorStream = process.getErrorStream();
            FileUtil.writeFromStream(stderr, errorStream);

            // 4. 等待进程执行完毕
            int code = process.waitFor();
            return code;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

}
